const router = require('koa-router')()
const mongoose = require('mongoose')
const upload = require('../upload')

router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')

router.post('/', upload.single('imgfile'), async ctx => {
  const {title, description} = ctx.req.body
  const {originalname, mimetype, filename: diskfilename} = ctx.req.file
  const doc = await Image.create({
    title, description, originalname, mimetype, diskfilename
  })
  ctx.redirect(`/images/show/${doc._id}`)
})

router.get('/show/:id', async ctx => {
  const doc = await Image.findById(ctx.params.id)
  doc.comments = await Comment.find({image: ctx.params.id})
    .sort({createdAt: -1})
  await ctx.render('show', doc)
})

router.post('/likes/:id', async ctx => {
  ctx.body = await Image.findByIdAndUpdate(
    ctx.params.id,
    {$inc: {likes: 1}},
    {new: true}
  )
})

module.exports = router